<template>
  <div class="login-container">
    <!-- 左边蓝色背景区域 -->
    <div class="left-section">
      <div class="left-content">
        <h1>家庭医生后台管理系统</h1>
        <div class="icon-container">
          <el-icon class="red-cross-icon"><Promotion /></el-icon>
        </div>
      </div>
    </div>

    <!-- 右边白色背景区域 -->
    <div class="right-section">
      <div class="right-content">
        <h2>欢迎登录</h2>

        <el-tabs v-model="activeTab" class="login-tabs">
          <el-tab-pane label="密码登录" name="password">
            <el-form :model="loginForm" :rules="rules" ref="passwordForm">
              <el-form-item prop="phone">
                <el-input
                    v-model="loginForm.phone"
                    placeholder="请输入电话"
                    prefix-icon="el-icon-phone"
                ></el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                    v-model="loginForm.password"
                    placeholder="请输入密码"
                    prefix-icon="el-icon-lock"
                    show-password
                ></el-input>
              </el-form-item>
              <el-form-item prop="code">
                <el-input
                    v-model="loginForm.code"
                    placeholder="请输入验证码"
                    prefix-icon="el-icon-key"
                    class="captcha-input"
                >
                  <template #append>
                    <div class="captcha-image" @click="refreshCaptcha">
                      <img :src="captchaImage" alt="验证码">
                    </div>
                  </template>
                </el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <el-tab-pane label="短信验证码登录" name="verification">
            <el-form :model="loginForm" :rules="rules" ref="verificationForm">
              <el-form-item prop="phone">
                <el-input
                    v-model="loginForm.phone"
                    placeholder="请输入电话"
                    prefix-icon="el-icon-phone"
                ></el-input>
              </el-form-item>
              <el-form-item prop="smsCode">
                <el-input
                    v-model="loginForm.smsCode"
                    placeholder="请输入短信验证码"
                    prefix-icon="el-icon-message"
                    class="verification-input"
                >
                  <template #append>
                    <el-button
                        :disabled="sending"
                        @click="sendSmsCode"
                    >
                      {{ sendText }}
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>

        <div class="agreement">
          <el-checkbox v-model="agreed">我已阅读并同意</el-checkbox>
          <el-link type="primary" @click="showPrivacyPolicy">《用户隐私政策》</el-link>
        </div>

        <div class="button-group">
          <el-button type="primary" :disabled="isButtonDisabled" @click="handleLogin">登录</el-button>
          <el-button type="warning" @click="register">注册</el-button>
        </div>
      </div>
    </div>

    <!-- 隐私政策对话框 -->
    <el-dialog
        title="用户隐私政策"
        v-model="privacyDialogVisible"
        width="50%"
    >
      <div class="privacy-content">
        <h3>用户隐私政策</h3>
        <p>最后更新日期：2023年11月1日</p>

        <p>感谢您使用家庭医生后台管理系统（以下简称"本系统"）。我们深知个人信息对您的重要性，并会尽全力保护您的个人信息安全可靠。</p>

        <h4>1. 我们收集的信息</h4>
        <p>在您使用本系统服务过程中，我们可能会收集以下信息：</p>
        <ul>
          <li>账号信息：包括您的手机号码、密码等。</li>
          <li>设备信息：包括设备型号、操作系统版本等。</li>
          <li>日志信息：包括您使用本系统的时间和持续时间等。</li>
        </ul>

        <h4>2. 信息的使用</h4>
        <p>我们可能将收集的信息用作以下用途：</p>
        <ul>
          <li>向您提供服务</li>
          <li>帮助我们改进服务</li>
          <li>安全保障</li>
        </ul>

        <h4>3. 信息的共享</h4>
        <p>我们不会与任何第三方分享您的个人信息，除非：</p>
        <ul>
          <li>获得您的明确授权</li>
          <li>根据法律法规要求</li>
        </ul>

        <p>如果您有任何疑问，请联系我们的客服人员。</p>
      </div>

      <template #footer>
        <el-button type="primary" @click="privacyDialogVisible = false">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, computed, onMounted, onUnmounted} from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
const router = useRouter();
import axios from "axios";

//pinia使用
import { userStore } from '/src/components/store/index.js'
const userItemStore = userStore();

import { messageStore } from '/src/components/store/message.js'
import {useWebSocket} from "@/composables/useWebSocket.js";
const messageItemStore = messageStore();

import request from '/src/utils/request';

//注册
const register=()=>{
  router.push('/register')
}


// 标签页控制
const activeTab = ref('password')

// 登录表单
const loginForm = ref({
  phone: '',
  password: '',
  code: '',
  smsCode: '',
  key:''
})

// 验证码图片
const captchaImage = ref('')


// 生成验证码图片
const generateCaptcha = () => {
  request.get(`/personalProfile/code`).then((response) => {
    captchaImage.value = response.data.base64Img;
    loginForm.value.key=response.data.key;
  })
}

// 刷新验证码
const refreshCaptcha = () => {
  generateCaptcha()
}

// 表单验证规则
const rules = {
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9]{4,6}$/, message: '请输入正确的验证码', trigger: 'blur' }
  ],
  smsCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{4}$/, message: '验证码为4位数字', trigger: 'blur' }
  ]
}

// 验证码倒计时
// 倒计时相关
const sending = ref(false)
const sendText = ref('发送验证码')
let countdown = 30

// 发送手机验证码
const sendSmsCode = () => {
  if (!loginForm.value.phone) {
    ElMessage.error('请输入手机号码')
    return
  }

  // 模拟发送验证码
  request.post(`/personalProfile/sendSms/${loginForm.value.phone}`).then((response) => {
    ElMessage.success(response.data)
  }).catch(error => {
    ElMessage.error(error.response.data);
  }).finally(()=>{
    sending.value = true
    const timer = setInterval(() => {
      countdown--
      sendText.value = `${countdown}s`
      if (countdown <= 0) {
        clearInterval(timer)
        sending.value = false
        sendText.value = '重新发送'
        countdown = 30
      }
    }, 1000)
  })
}

// 隐私政策相关
const agreed = ref(false)
const privacyDialogVisible = ref(false)

const showPrivacyPolicy = () => {
  privacyDialogVisible.value = true
}

//登陆按钮不可用
const isButtonDisabled = ref(false);

//处理未读公告
async function fetchUnreadAnnReceivers(userItemStore, messageItemStore) {
  // 确保 allConversations 存在且有数据
  if (!messageItemStore.allAnnReceivers || messageItemStore.allAnnReceivers.length === 0) {
    console.log('没有找到公告数据');
    return [];
  }

  // 筛选未读对话 - 修复用户对象引用
  messageItemStore.unreadAnnReceivers = messageItemStore.allAnnReceivers.filter(a => {
    return (
        a.readStatus===0
    );
  });
}

//处理未读对话
// 提取为独立函数，避免作用域问题
async function fetchUnreadMessages(userItemStore, messageItemStore) {
  // 确保 allConversations 存在且有数据
  if (!messageItemStore.allConversations || messageItemStore.allConversations.length === 0) {
    console.log('没有找到对话数据');
    messageItemStore.unreadConversations = []; // 确保清空未读对话
    return [];
  }

  // 筛选未读对话 - 修复用户对象引用
  const unreadConversations = messageItemStore.allConversations.filter(convo => {
    return (
        convo.latestMessageId != null &&
        convo.latestMessage?.senderId != null &&
        convo.latestMessage?.senderId != userItemStore.user.id &&
        convo.latestMessage?.isRead == 0
    );
  });

  // 如果没有未读对话，直接返回
  if (unreadConversations.length === 0) {
    messageItemStore.unreadConversations = [];
    return [];
  }

  try {
    // 为每个未读对话获取未读消息计数
    const requests = unreadConversations.map(conversation => {
      return request.get(`/message/getUnreadMessages/${conversation.id}/${userItemStore.user.id}`)
          .then(resp => ({
            ...conversation,
            unreadCount: resp.data,
            isReadCon: 0
          }))
          .catch(error => {
            console.error('获取未读消息失败:', error);
          });
    });

    // 等待所有请求完成
    // 更新store中的未读对话
    messageItemStore.unreadConversations = await Promise.all(requests);

  } catch (error) {
    console.error('处理未读消息时出错:', error);
    messageItemStore.unreadConversations = [];
    return [];
  }
}




// 登录处理
const handleLogin = async () => {
  if (!agreed.value) {
    ElMessage.warning('请先阅读并同意用户隐私政策')
    return
  }



  try {
    let response;
    if (activeTab.value === 'password') {

      // 密码登录验证
      response = await request.post("/personalProfile/login", loginForm.value);
    } else {
      // 验证码登录验证
      response = await request.post("/personalProfile/smsLogin", loginForm.value);
    }

    const user = response.data;
    if (user) {
      // 这里响应头大小写敏感，要写成小写
      localStorage.setItem('token', response.headers['authorization']);


      // 保存用户信息，转成字符串保存
      localStorage.setItem('user', JSON.stringify(user));

      // 存储用户
      userItemStore.updateUser(user);
      // 修改状态
      userItemStore.updateLoginStatus(true);
      // userItemStore.user.token = response.headers['authorization'];
      userItemStore.updateToken(response.headers['authorization']);


      //获取与更新公告和消息信息
      const [announcementsResp, conversationsResp] = await Promise.all([
        request.post(`/annReceiver/listForAnnReceiver/${userItemStore.user.id}`),
        request.post(`/conversation/getAllConversations/${userItemStore.user.id}`)
      ]);

      messageItemStore.allAnnReceivers = announcementsResp.data;

      messageItemStore.allConversations = conversationsResp.data;

      // alert(messageItemStore.allConversations[0].participantId)

      messageItemStore.allConversations = messageItemStore.allConversations.map(conversation => ({
        ...conversation,
        isReadCon: 1
      }));


      // 在登录成功之前调用
      // 登录成功后建立WebSocket连接（如果尚未建立）
      if (useWebSocket) {
        const { connect } = useWebSocket();
        connect();
      }

      // 正确调用应该传入参数
      await fetchUnreadMessages(userItemStore, messageItemStore);
      await fetchUnreadAnnReceivers(userItemStore, messageItemStore);

      //更新上线状态
      request.put(`/doctor/online/${userItemStore.user.id}`).then(resp=>{
        ElMessage.success(resp.data);
      })


      // 提示登录成功
      ElMessage({
        message: `登录成功，欢迎您：${user.username}！`,
        type: 'success'
      });
      await router.push('/main'); // 跳转到主页面
      isButtonDisabled.value = true;
      // 5秒后变得可用
      setTimeout(() => {
        isButtonDisabled.value = false;
      }, 5000);


    }
  } catch (error) {
    ElMessage.error(error.response?.data || '登录失败');
    // 刷新验证码
    if (activeTab.value == 'password') {
      refreshCaptcha();
    }
  }
}

// 取消处理
const handleCancel = () => {
  loginForm.value = {
    phone: '',
    password: '',
    code: '',
    smsCode: ''
  }
}

// 组件挂载时生成验证码
onMounted(() => {
  generateCaptcha()
})


</script>

<style scoped>
.login-container {
  display: flex;
  height: 100vh;
}

.left-section {
  flex: 1;
  background-color: #409EFF;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  color: white;
  padding-top: 10%;
}

.left-content {
  text-align: center;
  padding: 20px;
}

.left-content h1 {
  font-size: 2.5rem;
  margin-bottom: 2rem;
}

.icon-container {
  margin-top: 3rem;
}

.red-cross-icon {
  font-size: 12rem;
  color: white;
}

.right-section {
  flex: 1;
  background-color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}

.right-content {
  width: 70%;
  max-width: 400px;
}

.right-content h2 {
  text-align: center;
  margin-bottom: 2rem;
  color: #333;
}

.login-tabs {
  margin-bottom: 1.5rem;
}

.agreement {
  display: flex;
  align-items: center;
  margin-bottom: 1.5rem;
}

.agreement .el-checkbox {
  margin-right: 5px;
}

.button-group {
  display: flex;
  justify-content: space-between;
}

.button-group .el-button {
  width: 48%;
}

.privacy-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 10px;
}

.privacy-content h3 {
  text-align: center;
  margin-bottom: 1rem;
}

.privacy-content h4 {
  margin: 1rem 0 0.5rem;
}

.privacy-content p, .privacy-content ul {
  margin-bottom: 0.5rem;
  line-height: 1.6;
}

.privacy-content ul {
  padding-left: 20px;
}

.verification-input {
  :deep(.el-input-group__append) {
    padding: 0;
    border: none;

    .el-button {
      padding: 0 15px;
      height: 100%;
    }
  }
}

.captcha-input {
  :deep(.el-input-group__append) {
    padding: 0;
    overflow: hidden;
    cursor: pointer;

    .captcha-image {
      height: 100%;
      display: flex;
      align-items: center;

      img {
        height: 100%;
        width: auto;
      }
    }
  }
}
</style>